<?php
class GroupsController extends AppController {
	public $name = 'Groups';
	public $uses=array('Group','Aco','Aro');
	
	function admin_index(){
		//get filter field
		//filterField dùng cho combobox search của trang liet ke danh sach, khai bao cac field co the search cua danh sach. 
		$filterField=array(				
			$this->uses[0].'.name'=>_resource('name',true),	
		);
		$this->set('filterField',$filterField);
		
	}	
	
	function admin_lists(){
		$user=$this->Auth->user();
		//init session
		//khoi tao cac session se dung trong 1 model dung de luu lai page, sort, filter, condition ...
		if(!$this->Session->check($this->uses[0].'.limit')){
			$tmp=array(
				'limit'=>$this->webConfig['default_row_per_page'],
				'conditions'=>array($this->uses[0].'.site_id >'=>$user['User']['group_id']==1?0:1),
				'fields'=>null,
				'order'=>null,
				'page'=>1,
				'recursive'=>0,
				'sortField'=>null,
				'sortDir'=>'asc',				
				'filterField'=>'',
				'filterText'=>'',
				'catid'=>'',
			);
			//luu vao session			
			$this->Session->write($this->uses[0],$tmp);			
		}		
		//get data
		//lay condition, order, page, sort, filter... tu trong session de chuan bi cho ham phan trang  		
		$this->paginate=$this->Session->read($this->uses[0]);
		//lay du lieu va phan trang.
		$data0=$this->paginate($this->uses[0]);
		$this->set('data0',$data0);
		//render view
		$this->render('admin_lists','ajax');
	}
	
	function admin_add(){
		$this->{$this->uses[0]}->recursive=0;
		
		$isInsert=false;
		if(!empty($this->data)){
			if($this->{$this->uses[0]}->create($this->data) && $this->{$this->uses[0]}->validates()){
				$data=$this->{$this->uses[0]}->findByName($this->data[$this->uses[0]]['name']);
				if($data){
					$this->Session->write('error',_resource('error',true));
					$this->{$this->uses[0]}->invalidate('name');
				}
				else{
						
						$this->data[$this->uses[0]]['name']=htmlspecialchars($this->data[$this->uses[0]]['name']);
						$this->data[$this->uses[0]]['site_id']=2;						
						if($this->{$this->uses[0]}->save($this->data)) {
							$this->data=null;
							$isInsert=true;
							$this->Session->write('message',_resource('insert data successful',true));						
							
						} else {
							$this->Session->write('error',_resource('can not insert data',true));
						}
					}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}
		$this->set('isInsert',$isInsert);
		
	}

	function admin_edit($id=null){
		$user=$this->Auth->user();
		
		$group =& $this->Group;
		$group->id=$id;	
		
		if(Configure::read('Session.isSa'))$isShowSystemModule=true;
		else $isShowSystemModule=$this->Acl->check(array('Group'=>array('id'=>$user['group_id'])),'Groups/admin_showSystemModule','read');
		
		$this->{$this->uses[0]}->recursive=0;
		
		$isInsert=false;
		if(!empty($this->data)){
			//t($this->data);
			if($this->{$this->uses[0]}->create($this->data) && $this->{$this->uses[0]}->validates()){
				$data=$this->{$this->uses[0]}->findByName($this->data[$this->uses[0]]['name']);				
				if($data && $data[$this->uses[0]]['id']!=$this->data[$this->uses[0]]['id']){
					$this->Session->write('error',_resource('error',true));
					$this->{$this->uses[0]}->invalidate('name');
				}
				else{						
						$this->data[$this->uses[0]]['name']=htmlspecialchars($this->data[$this->uses[0]]['name']);						
						if($this->{$this->uses[0]}->save($this->data)) {
							//save aco for this group							
							unset($this->data['Group']);	
							//t($this->data);								
							$allAco=$this->Aco->generateTreeList(null,"{n}.Aco.id","{n}.Aco.alias","%");
							
										
											
							
							$parentName='';//luu ten cua aco cha.
							$isCheckAll=false;//luu lai de xet co check all hay ko
							foreach($allAco as $k=>$v){
								//khoi tao cac bien can thiet 
								$count=0;//dung de dem so luong % tim thay de check xem aco la node cha hay node con
								$name='';//luu ten cua aco 
								 
								//check controllers de loai bo node root, ko check node root
								if($v!='controllers'){
									$name=preg_replace("/\%/i","",$v,-1,$count);
									//neu count=1 thi node aco la node cha
									if($count==1){
										//check is system module			
										$isSystem=$this->Common->isSystemModule($name);
										//if module is system and no permission then skip
										if($isSystem && !$isShowSystemModule)continue;
										//reset is check all
										$isCheckAll=false;
										//luu lai ten cho node cha de su dung lai
										$parentName=$name;
										//kiem tra xem co data check tu form submit hay ko, neu co thi allow, nguoc lai thi deny aco
										if($this->data[$name]['all']){
											$this->Acl->allow($group,$name);
											$isCheckAll=true;
										}
										else{
											$this->Acl->deny($group,$name);
										}										
									}
									//neu count=2 thi node aco la node con
									if($count==2){
										//if module is system and no permission then skip
										if($isSystem && !$isShowSystemModule)continue;
										//kiem tra xem co data check tu form submit hay ko, neu co thi allow, nguoc lai thi deny aco
										if($this->data[$parentName][$name]){
											$this->Acl->allow($group,$parentName.'/'.$name);
											//neu node cha co 1 node con co quyen thi set quyen read cho node cha
											$this->Acl->allow($group,$parentName,'read');
										}
										else{
											if($isCheckAll)$this->Acl->allow($group,$parentName.'/'.$name,'read');
											else $this->Acl->deny($group,$parentName.'/'.$name);
										}
									}
								}
								
								
							}	
							
							$this->data=null;
							$isInsert=true;							
							$this->Session->write('message',_resource('update data successful',true));						
						} else {
							$this->Session->write('error',_resource('can not update data',true));
						}
					}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}else{
			if($id!=null){
				$this->data=$this->{$this->uses[0]}->findById($id);	
				
				if(empty($this->data)){		
					$this->Session->write('error',_resource('data not found',true));			
					$this->render('admin_edit_not_found');
				}
			}
			else{				
				$this->Session->write('error',_resource('data not found',true));		
				$this->render('editNotFound');
			}
		}	
		
		
		$this->Aco->recursive=0;
		
		//get group
		/*
		$this->Aro->recursive=0;
		$usergroup=$this->Aro->findById($id);		
		
		$options['joins']=array(
		'table'=>'aros_acos',
		'alias'=>'Permission',
		'type'=>'LEFT',
		'conditions'=>array('Aco.id = Permission.aco_id',
							'Permission.aro_id'=>$usergroup['Aro']['id']
							)
		);
		$options['order']='lft';
			$data=$this->Aco->find('all',$options);
			//t($data);
		*/
		
		$this->set('isInsert',$isInsert);
		//code for get all aco
		$groupAco="";
		$groupAcoSystem="";
		if(!$isInsert){
			$data=$this->Aco->generateTreeList(null,"{n}.Aco.id","{n}.Aco.alias",'%');
			$groupAco='';
			$groupAcoCount=0;
			$groupAcoCon="<div style=\"display:none\">
							<fieldset class=\"sub\"><legend class=\"sub\"></legend>
							<table class=\"form\">
								<tbody>";
			$groupAcoWebsite='';
			$groupAcoWebsiteCount=0;
			$groupAcoWebsiteCon="<div style=\"display:none\">
							<fieldset class=\"sub\"><legend class=\"sub\"></legend>
							<table class=\"form\">
								<tbody>";
			$groupAcoSystem='';
			$groupAcoSystemCount=0;
			$groupAcoSystemCon="<div style=\"display:none\">
							<fieldset class=\"sub\"><legend class=\"sub\"></legend>
							<table class=\"form\">
								<tbody>";
			$parentName='';
			
			$isCheckParent=false;//bien de luu lai trang thai cua permission cua node cha
			$isCheckParentRead=false;//bien de luu lai trang thai cua permission read cua node cha
			foreach($data as $k=>$v){
				
				//khai bao bien
				$count=0;//bien de xac dinh node cha hay con								
				$name=preg_replace("/%/i","",$v,-1,$count);
				
					
				//neu count la 1 thi do la node cha
				if($count==1){
					//check is system module			
					$isSystem=$this->Common->isSystemModule($name);
					
					//$isSystem=false;
					//luu lai ten cua node cha de su dung check node con
					$parentName=$name;
					//reset lai bien isCheckParent
					$isCheckParent=false;
					$isCheckParentRead=false;
					$checked='';//bien de xac dinh co check vao o checkbox hay khong
					$scripts='';//ma javascript de checkall
					if($this->Acl->check($group,$name)){
						$isCheckParent=true;//ghi nho lai permission cua node cha
						$checked="checked='check'";
						$scripts='<script>changestate("'.$name.'")</script>';
					}	
					//neu node cha co quyen read thi luu lai trang thai				
					else if($this->Acl->check($group,$name,'read')){
						$isCheckParentRead=true;
					}
					if($isSystem){
						if($groupAcoSystemCount)
						{
							$groupAcoSystemCon.="</tbody></table>
								</fieldset>
							</div>";
							$groupAcoSystem.=$groupAcoSystemCon;
						}		
						$groupAcoSystemCount=0;				
						$groupAcoSystemCon='';
					}
					else{
						if($groupAcoCount)
						{
							$groupAcoCon.="</tbody></table>
								</fieldset>
							</div>";
							$groupAco.=$groupAcoCon;
						}		
						$groupAcoCount=0;				
						$groupAcoCon='';
						
						if($groupAcoWebsiteCount)
						{
							$groupAcoWebsiteCon.="</tbody></table>
								</fieldset>
							</div>";
							$groupAcoWebsite.=$groupAcoWebsiteCon;
						}	
						$groupAcoWebsiteCount=0;					
						$groupAcoWebsiteCon='';						
						
					}
					if($isSystem){
						$groupAcoSystemCon.="<div style=\"width:250px;float:left\">
							<fieldset class=\"sub\"><legend class=\"sub\">".$name."</legend>
							<table class=\"form\">
								<tbody>
									<tr>					
										<td colspan=\"2\"><input class=\"checkbox\" type=\"checkbox\" id=\"".$name."All\" value=\"1\" onclick=\"changestate('".$name."')\" name=\"data[".$name."][all]\" ".$checked." />".$scripts."		</td>
										<td class=\"label\" style=\"background-color: rgb(150, 205, 161);text-align:left;border-left:1px solid #E9E9E9;padding-left:5px;border-right:none\" width=\"200px\">"._resource('all permission',true)."</td>
									</tr>";
					}
					else{						
						$groupAcoCon.="<div style=\"width:250px;float:left\">
							<fieldset class=\"sub\"><legend class=\"sub\">".$name."</legend>
							<table class=\"form\">
								<tbody>
									<tr>					
										<td colspan=\"2\"><input class=\"checkbox\" type=\"checkbox\" id=\"".$name."All\" value=\"1\" onclick=\"changestate('".$name."')\" name=\"data[".$name."][all]\" ".$checked." />".$scripts."		</td>
										<td class=\"label\" style=\"background-color: rgb(150, 205, 161);text-align:left;border-left:1px solid #E9E9E9;padding-left:5px;border-right:none\" width=\"200px\">"._resource('all permission',true)."</td>
									</tr>";
						$groupAcoWebsiteCon.="<div style=\"width:250px;float:left\">
							<fieldset class=\"sub\"><legend class=\"sub\">".$name."</legend>
							<table class=\"form\">
								<tbody>
									<tr>					
										<td colspan=\"2\"></td>
										<td class=\"label\" style=\"background-color: rgb(150, 205, 161);text-align:left;border-left:1px solid #E9E9E9;padding-left:5px;border-right:none\" width=\"200px\">"._resource('permission',true)."</td>
									</tr>
									";
					}
				}
				//neu count la 2 thi la node con
				if($count==2){
					$checked='';//bien de xac dinh check vao o checkbox
					//deny node cha de lay duoc permission cua node con (hieu ung de check duoc nhung check box con ben trong khi checkall )
					$this->Acl->deny($group,$parentName);
					//kiem tra permission cua node con
					if($this->Acl->check($group,$parentName.'/'.$name)){
						$checked="checked='check'";
					}
					//neu node cha duoc allow thi allow permission cua node cha
					if($isCheckParent){
						$this->Acl->allow($group,$parentName);
					}
					//neu read thi se allow read
					if($isCheckParentRead){
						$this->Acl->allow($group,$parentName,'read');
					}
					if($isSystem){
						$groupAcoSystemCon.="<tr>					
							<td colspan=\"2\"><input type=\"checkbox\" id=\"".$parentName.$name."\" value=\"1\" class=\"checkbox ".$parentName."\" name=\"data[".$parentName."][".$name."]\" ".$checked."/>		</td>
							<td class=\"label\" style=\"text-align:left;border-left:1px solid #E9E9E9;padding-left:5px;border-right:none\"><label class=\"".$parentName."\">".$name."</label></td>
						</tr>";
						$groupAcoSystemCount++;
					}
					else if(strpos($name,"admin",0) === 0){
						$groupAcoCon.="<tr>					
							<td colspan=\"2\"><input type=\"checkbox\" id=\"".$parentName.$name."\" value=\"1\" class=\"checkbox ".$parentName."\" name=\"data[".$parentName."][".$name."]\" ".$checked."/>		</td>
							<td class=\"label\" style=\"text-align:left;border-left:1px solid #E9E9E9;padding-left:5px;border-right:none\"><label class=\"".$parentName."\">".$name."</label></td>
						</tr>";
						$groupAcoCount++;
					}
					else{
						$groupAcoWebsiteCon.="<tr>					
							<td colspan=\"2\"><input type=\"checkbox\" id=\"".$parentName.$name."\" value=\"1\" class=\"checkbox ".$parentName."\" name=\"data[".$parentName."][".$name."]\" ".$checked."/>		</td>
							<td class=\"label\" style=\"text-align:left;border-left:1px solid #E9E9E9;padding-left:5px;border-right:none\"><label class=\"".$parentName."\">".$name."</label></td>
						</tr>";
						$groupAcoWebsiteCount++;
					}					
				}			
			}			
		
			if($groupAcoSystemCount)
			{
				$groupAcoSystemCon.="</tbody></table>
					</fieldset>
				</div>";
				$groupAcoSystem.=$groupAcoSystemCon;
			}			
			if($groupAcoCount)
			{
				$groupAcoCon.="</tbody></table>
					</fieldset>
				</div>";
				$groupAco.=$groupAcoCon;
			}
			if($groupAcoWebsiteCount)
			{
				$groupAcoWebsiteCon.="</tbody></table>
					</fieldset>
				</div>";
				$groupAcoWebsite.=$groupAcoWebsiteCon;
			}					
		}

		if(!$isShowSystemModule)$groupAcoSystem='';
		$this->set('groupAco',$groupAco);
		$this->set('groupAcoSystem',$groupAcoSystem);
		$this->set('groupAcoWebsite',$groupAcoWebsite);
		
	}

	function admin_delete($id = null) {		
		$this->Session->delete('error');
		//if is submit:		
		if($this->request->is('post')){
			$id_arr=$this->data['check'];
		} else {
			$id_arr=null;
		}
		//if url
		if(intval($id)){
			$id_arr[$id]='';
		}
		if(count($id_arr)>0){
			//Xoa nhieu record
			$this->{$this->uses[0]}->query('delete from '.$this->{$this->uses[0]}->tablePrefix.$this->{$this->uses[0]}->table.' where id in ('.implode(',',array_keys($id_arr)).')' );			
		} else {
			$this->Session->write('error',_resource('no information to delete',true));
		}
		$this->admin_lists();				
	}
	
	function admin_published($id=null,$value=1,$field=0){
		$id_arr=null;
		$all=false;		
		switch($field){
			case 1: $fieldname='best';break;
			case 2: $fieldname='bestbuy';break;
			default: $fieldname='published';
		}
		if((!intval($value) && $value!=0) || intval($value)>1){
			$value=1;
		}
		
		//if is submit:		
		if($this->request->is('post')){
			$id_arr=$this->data['check'];
			$all=true;
		} 
		
		//if url
		if(intval($id) && !$all){
			$id_arr[$id]='';
		}
		
		if(count($id_arr)>0){			
			$this->{$this->uses[0]}->query('update '.$this->{$this->uses[0]}->tablePrefix.$this->{$this->uses[0]}->table.' set '.$fieldname.'='.$value.' where id in ('.implode(',',array_keys($id_arr)).')' );
		}
		if (!$all) {			
			$this->set('value',$value);
			$this->set('field',$field);
			$this->set('fieldname',$fieldname);
			$this->set('id',intval($id));
			$this->render('admin_published','ajax');		
		} else {
			$this->admin_lists();
		}
		
	}
	
	function admin_sort($sortField=null,$sortDir='asc'){
		if($sortField){
			if($sortDir!='desc') $sortDir='asc';
			$this->Session->write($this->uses[0].'.sortField',$sortField);
			$this->Session->write($this->uses[0].'.sortDir',$sortDir);
			$this->Session->write($this->uses[0].'.order',$sortField.' '.$sortDir);
		}
		$this->admin_lists();
	}
	
	function admin_page($page=1){
		$this->Session->write($this->uses[0].'.page',$page);
		$this->admin_lists();
	}
	
	function admin_display($limit=0){
		if(intval($limit)){
			$this->Session->write($this->uses[0].'.limit',$limit);
		}
		$this->admin_lists();
	}

	function admin_filter(){
		if($this->request->is('post')){
			$this->Session->write($this->uses[0].'.filterText',$this->request->data['filter_text']);
			$this->Session->write($this->uses[0].'.filterField',$this->request->data['filter_field']);
			$conditions=$this->Session->read($this->uses[0].'.conditions');
			if(!empty($this->request->data['filter_text'])){				
				$conditions[$this->request->data['filter_field'].' like']='%'.$this->request->data['filter_text'].'%';				
			}
			else{
				unset($conditions[$this->request->data['filter_field'].' like']);
			}			
			$this->Session->write($this->uses[0].'.conditions',$conditions);
		}
		$this->admin_lists();
	}	
	
	function admin_showSystemModule(){
	
	}

	//===========================================================

	

}
?>
